<template>
  <div class="app-container" style="background: #FFFFFF; ">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="渠道ID" prop="deaId" v-if="false">
        <el-input v-model="queryParams.deaId" placeholder="请输入渠道ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customer">
        <el-input v-model="queryParams.customer" placeholder="请输入实名认证名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户帐号" prop="accountName">
        <el-input v-model="queryParams.accountName" placeholder="请输入客户帐号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户类型" prop="associationType">
        <el-select v-model="queryParams.associationType" style="width: 100%;" filterable placeholder="客户类型" clearable>
          <el-option v-for="dict in dict.type.kh_gllx" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-back" size="mini" @click="backqd"
          v-show="showback">返回渠道列表</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['CustomerinfoMain:customerinfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['CustomerinfoMain:customerinfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['CustomerinfoMain:customerinfo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="multiple" @click="ywyplfp"
          v-hasPermi="['CustomerinfoMain:customerinfo:fp']">批量分配</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['CustomerinfoMain:customerinfo:export']">导出</el-button>
      </el-col>
   
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerinfoList" @selection-change="handleSelectionChange"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }" border="">
     
      <el-table-column label="客户账号ID" align="center" prop="customerId" v-if="false" />
      <el-table-column label="所属经销商" align="center" prop="deaId" v-if="false" />
      <el-table-column label="客户名称/帐号名" align="left" prop="accountName">
        <template slot-scope="scope">
          <div style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">{{ scope.row.customer }}</div>
          <span style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">
            {{ scope.row.accountName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="等级" align="center" prop="customerLevel" width="60" />
      <el-table-column label="电话" align="center" prop="telephone" width="100" />
      <el-table-column label="可用额度" align="center" v-if="false" />
      <el-table-column label="关联类型" align="center" prop="associationType" width="80">
        <template slot-scope="scope">
            <span style="white-space: pre-wrap;">
                        {{ scope.row.associationType == '1' ? '推荐' : '转售' }}
                      </span>

        </template>

      </el-table-column>
      <el-table-column label="关联时间" align="center" prop="associatedOn" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.associatedOn, '{y}-{m}-{d} {hh}:{mm}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实名认证名称" align="center" prop="customer" v-if="false" />


      <el-table-column label="认证状态" align="center" prop="verifiedStatus" width="90">
        <template slot-scope="scope">
          <span slot="reference" v-if="scope.row.verifiedStatus == -1">
            <div class="dotClass" style="background-color: #2395d0;"> </div>
            <div style="float: left; margin-left: 10px;">未认证</div>
          </span>
          <span slot="reference" v-if="scope.row.verifiedStatus == 2">
            <div class="dotClass" style="background-color: #00cdaa;"> </div>
            <div style="float: left; margin-left: 10px;">已认证</div>
          </span>
          <span slot="reference" v-if="scope.row.verifiedStatus == 3">
            <div class="dotClass" style="background-color: red;"> </div>
            <div style="float: left; margin-left: 10px;">认证失败</div>
          </span>
          <span slot="reference" v-if="scope.row.verifiedStatus == 1">
            <div class="dotClass" style="background-color:#ff7e27;"> </div>
            <div style="float: left; margin-left: 10px;">不通过</div>
          </span> <span slot="reference" v-if="scope.row.verifiedStatus == 0">
            <div class="dotClass" style="background-color:blueviolet;"> </div>
            <div style="float: left; margin-left: 10px;">审核中</div>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="客户标签" align="left" prop="label" v-if="false" />
      <el-table-column label="关联渠道" align="left" prop="deaName">
        <template slot-scope="scope">
          <div :title="scope.row.deaName" style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">{{
            scope.row.deaName }}</div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="实际渠道" align="left" prop="realDeaName">
        <template slot-scope="scope">
          <div :title="scope.row.realDeaName" style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">{{
            scope.row.realDeaName }}</div>
        </template>
      </el-table-column> -->
      <el-table-column label="负责业务员" align="left" prop="showaccountName">
        <template slot-scope="scope">
          <el-tooltip placement="top">
            <div slot="content">{{ scope.row.showaccountName }}</div>
            <div>
              <div style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">{{ scope.row.showaccountName }}
              </div>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      
      <el-table-column label="国家码" align="center" prop="countryCode" v-if="false" />
      <el-table-column label="客户类型" align="center" prop="customerType" v-if="false" />
      <el-table-column label="是否冻结(0否1是）" align="center" prop="isFrozen" v-if="false" />

      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180px" fixed="right">
        <template slot-scope="scope">

          <el-button size="mini" type="text" icon="el-icon-file" @click="finddd(scope.row)">查看订单</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['CustomerinfoMain:customerinfo:fp']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">分配</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleResetPwd" icon="el-icon-key">分配业务员</el-dropdown-item>
              <el-dropdown-item command="handleAuthRole" icon="el-icon-circle-check">分配实际渠道</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属经销商" prop="deaId" v-if="false">
          <el-input v-model="form.deaId" placeholder="请输入所属经销商ID" />
        </el-form-item>
        <el-form-item label="登录名" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入登录名" />
        </el-form-item>
        <el-form-item label="实名认证" prop="customer">
          <el-input v-model="form.customer" placeholder="请输入实名认证名称" />
        </el-form-item>
        <el-form-item label="关联时间" prop="associatedOn">
          <el-input v-model="form.associatedOn" placeholder="请输入关联时间" />
        </el-form-item>
        <el-form-item label="标签" prop="label">
          <el-input v-model="form.label" placeholder="请输入标签" />
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入电话" />
        </el-form-item>



        <el-form-item label="客户等级" prop="customerLevel">
          <el-input v-model="form.customerLevel" placeholder="请输入客户等级" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 分配业务员弹窗测试 -->
    <el-dialog :title="title1" :visible.sync="open1" width="500px" append-to-body>
      <el-form :model="queryParamsUser" ref="queryFormUser" size="small" :inline="true" label-width="68px"
        @submit.native.prevent>
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="queryParamsUser.nickName" placeholder="请输入姓名" clearable
            @keyup.enter.native="handleUserQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryUser">重置</el-button>
        </el-form-item>
      </el-form>
      <el-form label-width="80px">
        <el-table v-loading="loading" style="overflow: auto; " height="400px" :data="dealeruser"
          @selection-change="handleSelectionChangeUser" ref="multipleTable">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="编号" align="center" prop="userId" />
          <el-table-column label="帐号" align="center" prop="userName" />
          <el-table-column label="姓名" align="center" prop="nickName" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="ywyClick">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配渠道弹窗测试 -->
    <el-dialog :title="title2" :visible.sync="open2" width="1000px" append-to-body>
      <el-form :model="queryParamsQd" ref="queryFormQd" size="small" :inline="true" label-width="68px"
        @submit.native.prevent>
        <el-form-item label="渠道名称" prop="deaName">
          <el-input v-model="queryParamsQd.deaName" placeholder="请输入渠道名称" clearable @keyup.enter.native="handleQdQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQdQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryQd">重置</el-button>
        </el-form-item>
      </el-form>
      <el-form label-width="80px">
        <el-table v-loading="loading" style="overflow: auto; " height="400px" :data="dealerList"
          @selection-change="handleSelectionChangeQd">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="渠道编号" align="center" prop="deaId" />
          <el-table-column label="渠道名称" align="center" prop="deaName" />
          <el-table-column label="帐号" align="center" prop="deaUser" />
        </el-table>
        <pagination v-show="total2 > 0" :total="total2" :page.sync="queryParamsQd.pageNum"
          :limit.sync="queryParamsQd.pageSize" @pagination="getListDea" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="qdClick">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCustomerinfoa, listoutCustomerinfo, getCustomerinfo, delCustomerinfo, addCustomerinfo, updateCustomerinfo, tblistCustomerinfo, tblistCustomerinfoywy, selectyh,selectyhs, updateqd } from "@/api/CustomerinfoMain/customerinfo";
import {
  listDealerAll,
} from "@/api/DealerMain/dealer";
import { listuser, getUserProfile } from "@/api/system/user";
import { listCustomerinfouser } from "@/api/CustomerinfoUserMain/customerinfouser";
export default {
  dicts: ["kh_gllx"],
  name: "Customerinfo",
  data() {
    return {
      checked: false,
      showback: false,

      deaval: {//分配时，传值的parm
        deaIdpa: null,
        deaIdpb: null,
        deaIdpc: null,
        deaIdpd: null,
        customerId: null,
      },

      custuserparm: {
        customerId: null,
        pageSize: 30,
      }, //获取选中业务员参数
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 客户表格数据
      customerinfoList: [],
      // 下级客户表格数据
      customerinfoLista: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,


      //分配业务员选中相关
      dealeruser: [],
      ywyid: [],//分配选中的业务员
      ywyname: [],
      ywycode: [],
      idsdeaid: '',
      open1: false,
      queryParamsUser: {
        nickName: null,
      },
      title1: "",

      //分配渠道相关
      open2: false,
      title2: "",
      dealerList: [],
      deid: [],//分配选中的渠道
      qdval: {//分配时，传值的parm
        deaId: null,
        realDea: null,
      },
      total2: 0,
      // 查询参数
      queryParamsQd: {
        pageNum: 1,
        pageSize: 10,
        Dtype: 2,
        deaName: null,
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deaId: null,
        accountName: null,
        customer: null,
        associatedOn: null,
        associationType: null,
        label: null,
        telephone: null,
        verifiedStatus: null,
        countryCode: null,
        customerType: null,
        isFrozen: null,
        accountManagers: null,
        xaccountId: null,
        xaccountType: null,
        customerLevel: null,
        other1: null,
        other2: null,
        other3: null,
        other4: null,
        other5: null
      },


      usertype: "",

      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {

    this.queryParams.deaId = this.$route.query.did;

    if (this.queryParams.deaId != undefined) {
      this.showback = true;
      //执行查询搜索事件
      this.handleQuery();
    }
    else
      this.getList();

  },
  methods: {
    //返回渠道列表
    backqd: function () {

      this.$router.push(
        {
          path: '/dealer/dealerhw',
          methods: 'post',
          query: {
            a: "02",
          }
        })
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    //获取用户类型 --好像没用到了
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.usertype = this.user.usertype;
        // if(this.usertype=="00")
        // {
        // 	 this.activeName = "second1";
        // }
      });
    },
    /** 查询客户列表 */
    getList() {

      this.loading = true;
      listoutCustomerinfo(this.queryParams).then(response => {
        this.customerinfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    finddd: function (row) {
      let routeData = this.$router.resolve({ path: '/ddgl/customerorder2', query: { did: row.customer, } });
      window.open(routeData.href, '_blank');
      // this.$router.push(
      //   {
      //     path: '/ddgl/customerorder',
      //     methods: 'post',
      //     query: {
      //       did: row.customer,
      //     }
      //   })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancel1() {
      this.open1 = false;
      this.getList();
      this.reset();
    },
    cancel2() {
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        customerId: null,
        deaId: null,
        accountName: null,
        customer: null,
        associatedOn: null,
        associationType: null,
        label: null,
        telephone: null,
        verifiedStatus: null,
        countryCode: null,
        customerType: null,
        isFrozen: null,
        accountManagers: null,
        xaccountId: null,
        xaccountType: null,
        customerLevel: null,
        other1: null,
        other2: null,
        other3: null,
        other4: null,
        other5: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.checked == true)
          this.queryParams.other3 = 1;
        else
          this.queryParams.other3 = null;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /**分配业务员窗口重置 */
    resetQueryUser() {
      this.resetForm("queryFormUser");
      this.handleUserQuery();
    },
    /**分配渠道窗口重置 */
    resetQueryQd() {
      this.resetForm("queryFormQd");
      this.handleQdQuery();
    },
    /** 搜索按钮操作 */
    handleUserQuery() {
      this.getListuser();
    },
    /** 搜索按钮操作 */
    handleQdQuery() {
      this.getListDea();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.customerId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const customerId = row.customerId || this.ids
      getCustomerinfo(customerId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.customerId != null) {
            updateCustomerinfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomerinfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const customerIds = row.customerId || this.ids;
      this.$modal.confirm('是否确认删除客户编号为"' + customerIds + '"的数据项？').then(function () {
        return delCustomerinfo(customerIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('CustomerinfoMain/customerinfo/export', {
        ...this.queryParams
      }, `customerinfo_${new Date().getTime()}.xlsx`)
    },
    /** 同步客户 */
    tbinfo() {
      // this.loading = true;
      // tblistCustomerinfo(this.queryParams).then((response) => {
      //   this.getList();
      //   this.loading = false;
      // });

      tblistCustomerinfo(this.queryParams);
      this.$modal.msgSuccess("任务已下发");
    },
    /** 同步客户对应的业务员 */
    tbkhtoywy() {
      this.loading = true;
      tblistCustomerinfoywy(this.queryParams).then((response) => {
        this.getList();
        this.loading = false;
      });
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    ywyplfp() {
      this.idsdeaid = '';
      this.open1 = true;
      this.title1 = "批量分配业务员";
      this.loading = true;
      listuser(this.queryParamsUser).then(response => {
        this.dealeruser = response.rows;
        this.loading = false;

      });

    },
    /** 批量分配业务员搞操作 */
    ywyClick() {
      this.deaval.deaIdpa = this.ywyid;
      this.deaval.deaIdpb = this.ywyname;
      this.deaval.deaIdpc = this.ywycode;
      if (this.ids.length == 0) {
        this.deaval.customerId = this.idsdeaid;
        selectyh(this.deaval).then(response => {
          this.open1 = false;
          this.$modal.msgSuccess("分配成功");
          this.getList();
        });
      }
      else {
        this.deaval.deaIdpd = this.ids;
        //表示批量
        selectyhs(this.deaval).then(response => {
          this.open1 = false;
          this.$modal.msgSuccess("分配成功");
          this.getList();
        });

      }
    },
    handleResetPwd(row) {
      this.ids = [];
      this.idsdeaid = row.customerId;
      this.open1 = true;
      this.title1 = "分配业务员";
      this.getListuser();
    },
    handleAuthRole(row) {
      this.idsdeaid = row.customerId;
      this.open2 = true;
      this.title2 = "分配渠道";
      this.getListDea();
    },
    /** 查询分配列表 */
    getListuser() {
      this.loading = true;
      listuser(this.queryParamsUser).then(response => {
        this.dealeruser = response.rows;

        //这里查询子表中绑定的数据，将选中项显示绑定
        this.custuserparm.customerId = this.idsdeaid;
        listCustomerinfouser(this.custuserparm).then(responseuser => {

          this.$nextTick(() => {
            this.dealeruser.forEach(row => {
              for (var i in responseuser.rows) {
                if (responseuser.rows[i].userId == row.userId) {
                  this.$refs.multipleTable.toggleRowSelection(row, true);
                }
              }
            });
          }
          )
          this.loading = false;
        });
      });
    },
    /** 查询分配渠道列表 */
    getListDea() {

      this.loading = true;
      listDealerAll(this.queryParamsQd).then((response) => {
        this.dealerList = response.rows;
        this.total2 = response.total;
        this.loading = false;

      });
    },

    /** 分配渠道搞操作 */
    qdClick() {

      if (this.deid.length > 1) {
        this.$modal.msgWarning("只能选择一个渠道");
        return;
      }

      this.qdval.realDea = this.deid[0];
      this.qdval.customerId = this.idsdeaid;

      updateqd(this.qdval).then(response => {
        this.open2 = false;
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });

    },
    // 分配弹窗多选框选中数据1
    handleSelectionChangeUser(selection) {
      this.ywyid = selection.map(item => item.userId)
      this.ywyname = selection.map(item => item.nickName)
      this.ywycode = selection.map(item => item.userName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    // 分配弹窗多选框选中数据1 渠道
    handleSelectionChangeQd(selection) {
      this.deid = selection.map(item => item.deaId)

      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
  }
};
</script>
<style>
.dotClass {
  width: 15px;
  height: 15px;
  float: left;
  margin-top: 3px;
  border-radius: 50%;
  display: block;

}

.el-table th.gutter {
  display: table-cell !important;
  /* 解决表头线未对齐 */
}
</style>